package hash_util

import "github.com/spaolacci/murmur3"

const base62Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
const SIZE = uint64(len(base62Chars))

// ConvertDecToBase62 将十进制数字转换为 Base62 字符串
func ConvertDecToBase62(num uint64) string {
	if num == 0 {
		return string(base62Chars[0])
	}

	buf := make([]byte, 0, 11) // 预分配缓冲区
	for num > 0 {
		remainder := num % 62
		buf = append(buf, base62Chars[remainder])
		num /= SIZE
	}

	// 反转结果字符串
	for i, j := 0, len(buf)-1; i < j; i, j = i+1, j-1 {
		buf[i], buf[j] = buf[j], buf[i]
	}
	return string(buf)
}

// HashToBase62 将字符串哈希为 Base62 编码
func HashToBase62(str string) string {
	// 计算 MurmurHash3 32 位哈希值
	hash32 := murmur3.Sum32([]byte(str))

	// 将哈希值转为正数
	num := uint64(hash32)
	if hash32 > 0x7FFFFFFF {
		num = uint64(0x7FFFFFFF) - (uint64(0xFFFFFFFF) - num)
	}

	return ConvertDecToBase62(num)
}
